package com.cn.yunhe.rentcars.web;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.cn.yunhe.rentcars.captcah.BusiLogUtil;
import com.cn.yunhe.rentcars.mapper.BusiLogMapper;
import com.cn.yunhe.rentcars.mapper.CarDeviceMapper;
import com.cn.yunhe.rentcars.mapper.CarMapper;
import com.cn.yunhe.rentcars.mapper.CarOwnerMapper;
import com.cn.yunhe.rentcars.mapper.CarPicMapper;
import com.cn.yunhe.rentcars.mapper.CarPriceMapper;
import com.cn.yunhe.rentcars.mapper.ClientUserMapper;
import com.cn.yunhe.rentcars.model.Car;
import com.cn.yunhe.rentcars.model.CarDevice;
import com.cn.yunhe.rentcars.model.CarPic;
import com.cn.yunhe.rentcars.model.CarPrice;
import com.cn.yunhe.rentcars.model.ClientUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@RestController
public class CarController {

    @Autowired
    private CarMapper carMapper;
    @Autowired
    private ClientUserMapper clientUserMapper;
    @Autowired
    private CarOwnerMapper carOwnerMapper;
    @Autowired
    private CarPriceMapper carPriceMapper;
    @Autowired
    private CarDeviceMapper carDeviceMapper;
    @Autowired
    private CarPicMapper carPicMapper;
    @Autowired
    private Environment env;
    /**
     * 注入日志操作
     */
    @Autowired
    private BusiLogMapper busiLogMapper;
    /**
     * 页面跳转到车辆审核列表
     * 
     * @return 页面
     */

    @RequestMapping(value = "/checkList", method = RequestMethod.GET)
    public ModelAndView showCheckListPage() {

        return new ModelAndView("check-list");
    }
    /**
     * 页面跳转到车辆上架列表
     * 
     * @return 页面
     */

    @RequestMapping(value = "/putawayList", method = RequestMethod.GET)
    public ModelAndView showPutAwayListPage() {

        return new ModelAndView("putaway-list");
    }
    /**
     * 车辆审核列表(支持分页)
     * 
     * @param carcode
     *            车牌号
     * @param mobile
     *            手机号
     * @param carstate
     *            车辆状态
     * @param draw
     *            【jquery datatable特有的固定参数：第几次点击查询】
     * @param start
     *            【jquery datatable特有的固定参数：从第几条数据开始查询】
     * @param length
     *            【jquery datatable特有的固定参数：每页多少条数据】
     * @return
     */
    @RequestMapping(value = "/checkList/getlikecond", method = RequestMethod.GET)
    public Map<String, Object> checkList(
            @RequestParam(required = false) String carcode,
            @RequestParam(required = false) String mobile,
            @RequestParam int draw, @RequestParam int start,
            @RequestParam int length) {
        // TODO:把输入参数封装为Map
        Map<String, String> paramsMap = new HashMap<String, String>();
        paramsMap.put("carcode", carcode);
        paramsMap.put("mobile", mobile);

        int pageNum = (start / length) + 1;// 获取当前查询第几页
        int pageSize = length;
        PageHelper.startPage(pageNum, pageSize);

        // TODO:调用DAO Mapper数据传入Map数据去模糊查询，返回List结果
        List<Car> checkList = carMapper.searchCheckCars(paramsMap);
        PageInfo<Car> page = new PageInfo<Car>(checkList);
        Map<String, Object> rsMap = new HashMap<String, Object>();
        rsMap.put("draw", draw);
        rsMap.put("data", page.getList());
        rsMap.put("recordsTotal", page.getTotal());
        rsMap.put("recordsFiltered", page.getTotal());

        return rsMap;
    }
    /**
    * @param carcode
     *            车牌号
     * @param mobile
     *            手机号
     * @param draw
     *            【jquery datatable特有的固定参数：第几次点击查询】
     * @param start
     *            【jquery datatable特有的固定参数：从第几条数据开始查询】
     * @param length
     *            【jquery datatable特有的固定参数：每页多少条数据】
     * @return 车辆上架页面
     */
    @RequestMapping(value = "/putawayList/getlikecond", method = RequestMethod.GET)
    public Map<String, Object> putawayList(
            @RequestParam(required = false) String carcode,
            @RequestParam(required = false) String mobile,
            @RequestParam int draw, @RequestParam int start,
            @RequestParam int length) {
        // TODO:把输入参数封装为Map
        Map<String, String> paramsMap = new HashMap<String, String>();
        paramsMap.put("carcode", carcode);
        paramsMap.put("mobile", mobile);

        int pageNum = (start / length) + 1;// 获取当前查询第几页
        int pageSize = length;
        PageHelper.startPage(pageNum, pageSize);

        // TODO:调用DAO Mapper数据传入Map数据去模糊查询，返回List结果
        List<Car> checkList = carMapper.searchPutawayCars(paramsMap);
        PageInfo<Car> page = new PageInfo<Car>(checkList);
        Map<String, Object> rsMap = new HashMap<String, Object>();
        rsMap.put("draw", draw);
        rsMap.put("data", page.getList());
        rsMap.put("recordsTotal", page.getTotal());
        rsMap.put("recordsFiltered", page.getTotal());

        return rsMap;
    }
    /**
     * 跳转新车添加页面
     */
    @RequestMapping(value = "/addNewCar", method = RequestMethod.GET)
    public ModelAndView showAddNewCarPage() {
        return new ModelAndView("car-add");
    }

    /**
     * 新车入册页面，添加车辆信息表，车辆车主表，客户信息表 添加新车辆方法 缺少细节处理，当数据库中有相同身份信息时不再添加相同数据
     */
    @RequestMapping(value = "/cars/add", method = RequestMethod.POST)
    public void addCar(@RequestParam(required = false) String carcode,
            @RequestParam String carcolor, @RequestParam String buydate,
            @RequestParam String enginenum, @RequestParam String framenum,
            @RequestParam String cartype, @RequestParam String carbrand,
            @RequestParam String carbrandtype,
            @RequestParam(required = false) String picid,
            @RequestParam String isauto, @RequestParam String enginesize,
            @RequestParam String seatnum, @RequestParam String facetype,
            @RequestParam String contractdate,
            @RequestParam(required = false) String mobile,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String idcard,
            @RequestParam(required = false) String carstate,
            HttpServletRequest request) {

    	String carid = UUID.randomUUID().toString();
        String clientid = UUID.randomUUID().toString();
        
        // TODO把车辆信息参数封装成Map
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("carcode", carcode);
        paramMap.put("carcolor", carcolor);
        paramMap.put("carid", carid);
        paramMap.put("enginenum", enginenum);
        paramMap.put("framenum", framenum);
        paramMap.put("cartype", cartype);
        paramMap.put("carbrand", carbrand);
        paramMap.put("carbrandtype", carbrandtype);
        paramMap.put("isauto", isauto);
        paramMap.put("enginesize", enginesize);
        paramMap.put("seatnum", seatnum);
        paramMap.put("facetype", facetype);
        paramMap.put("buydate", buydate);
        paramMap.put("contractdate", contractdate);
        paramMap.put("carstate", carstate);
        carMapper.addCar(paramMap);
        // TODO添加日志信息
        Map<String, Object> carMap = new HashMap<String, Object>();
        carMap.put("logid", UUID.randomUUID().toString());
        carMap.put("businame", "添加车辆信息");
        carMap.put("busitype", "添加");
        carMap.put("busiconent", "添加车辆信息");
        BusiLogUtil.addBusiLog(request, busiLogMapper, carMap);

        // TODO判断身份证号是否存在，如果存在不再将身份信息插入到客户表t_clientuser表中
        if (clientUserMapper.isexit(idcard) == 0) {
            // TODO添加客户信息
            Map<String, String> paramClient = new HashMap<String, String>();
            paramClient.put("uid", clientid);
            paramClient.put("name", name);
            paramClient.put("idcard", idcard);
            paramClient.put("mobile", mobile);
            clientUserMapper.addClient(paramClient);
            // TODO添加日志信息
            Map<String, Object> clientMap = new HashMap<String, Object>();
            clientMap.put("logid", UUID.randomUUID().toString());
            clientMap.put("businame", "添加客户信息");
            clientMap.put("busitype", "添加");
            clientMap.put("busiconent", "添加客户信息");
            BusiLogUtil.addBusiLog(request, busiLogMapper, clientMap);
            // TODO添加车辆车主表
            Map<String, String> paramOwner = new HashMap<String, String>();
            paramOwner.put("carid", carid);
            paramOwner.put("clientid", clientid);
            carOwnerMapper.addCarOwner(paramOwner);
            // TODO添加日志信息
            Map<String, Object> ownerMap = new HashMap<String, Object>();
            ownerMap.put("logid", UUID.randomUUID().toString());
            ownerMap.put("businame", "添加车辆车主信息");
            ownerMap.put("busitype", "添加");
            ownerMap.put("busiconent", "添加车辆车主信息");
            BusiLogUtil.addBusiLog(request, busiLogMapper, ownerMap);
 // TODO添加车辆图片信息
            
            String carpics = picid;
            String[] pics = carpics.split(",");
//            car.setPicid(pics[0]);
            for(String pic:pics){
            Map<String, String> paramPic = new HashMap<String, String>();
            paramPic.put("picId", pic.substring(0,pic.lastIndexOf(".")+1));
            paramPic.put("picUrl", env.getProperty("jkd.paths.readFiles"));
            paramPic.put("picName", pic);
            paramPic.put("carId", carid);
            carPicMapper.addCarPic(paramPic);
            }
            // TODO添加日志信息
            Map<String, Object> picMap = new HashMap<String, Object>();
            picMap.put("logid", UUID.randomUUID().toString());
            picMap.put("businame", "添加车辆图片信息");
            picMap.put("busitype", "添加");
            picMap.put("busiconent", "添加车辆图片信息");
            BusiLogUtil.addBusiLog(request, busiLogMapper, picMap);
            // TODO获取车辆图片的图片编号，插入到车辆信息表中
            Car car = new Car();
            car.setCarid(carid);
            car.setPicid(pics[0]);
            carMapper.addPicId(car);
            // TODO添加日志信息
            Map<String, Object> picidMap = new HashMap<String, Object>();
            picidMap.put("logid", UUID.randomUUID().toString());
            picidMap.put("businame", "添加车辆ID到车辆表");
            picidMap.put("busitype", "添加");
            picidMap.put("busiconent", "添加车辆ID到车辆表");
            BusiLogUtil.addBusiLog(request, busiLogMapper, picidMap);
        } else {
            // TODO添加车辆车主表
            Map<String, String> paramOwner = new HashMap<String, String>();
            paramOwner.put("carid", carid);
            paramOwner.put("clientid", clientid);
            carOwnerMapper.addCarOwner(paramOwner);
            // TODO添加日志信息
            Map<String, Object> ownerMap = new HashMap<String, Object>();
            ownerMap.put("logid", UUID.randomUUID().toString());
            ownerMap.put("businame", "添加车辆车主信息");
            ownerMap.put("busitype", "添加");
            ownerMap.put("busiconent", "添加车辆车主信息");
            BusiLogUtil.addBusiLog(request, busiLogMapper, ownerMap);
            // TODO添加车辆图片信息
            String carpics = picid;
            String[] pics = carpics.split(",");
//            car.setPicid(pics[0]);
            
            for(String pic:pics){
            Map<String, String> paramPic = new HashMap<String, String>();
            paramPic.put("picId", pic.substring(0,pic.lastIndexOf(".")+1));
            paramPic.put("picUrl", env.getProperty("jkd.paths.readFiles"));
            paramPic.put("picName", pic);
            paramPic.put("carId", carid);
            carPicMapper.addCarPic(paramPic);
            }
            // TODO添加日志信息
            Map<String, Object> picMap = new HashMap<String, Object>();
            picMap.put("logid", UUID.randomUUID().toString());
            picMap.put("businame", "添加车辆图片信息");
            picMap.put("busitype", "添加");
            picMap.put("busiconent", "添加车辆图片信息");
            BusiLogUtil.addBusiLog(request, busiLogMapper, picMap);
            // TODO获取车辆图片的图片编号，插入到车辆信息表中
            Car car = new Car();
            car.setCarid(carid);
            car.setPicid(pics[0]);
            carMapper.addPicId(car);
            // TODO添加日志信息
            Map<String, Object> picidMap = new HashMap<String, Object>();
            picidMap.put("logid", UUID.randomUUID().toString());
            picidMap.put("businame", "添加车辆ID到车辆表");
            picidMap.put("busitype", "添加");
            picidMap.put("busiconent", "添加车辆ID到车辆表");
            BusiLogUtil.addBusiLog(request, busiLogMapper, picidMap);
        }
    }
    /**
     * @param carid
     *            车辆编号
     * @return 车辆审核列表-点击审核按钮弹出子页面：审核页面
     */
    @RequestMapping(value = "/check-edit", method = RequestMethod.GET)
    public ModelAndView showEditCheck(@RequestParam String carid) {
        Car car = carMapper.getCarByCarid(carid);
        Map<String, Object> carMap = new HashMap<String, Object>();
        carMap.put("car", car);

        // TODO根据clientid获取到ClientUser信息
        ClientUser clientUser = clientUserMapper.getClientByuid(carOwnerMapper
                .getClientid(carid));
        carMap.put("clientUser", clientUser);

        return new ModelAndView("check-edit", carMap);
    }

    /**
     * @return 车辆审核列表-点击上架按钮弹出上架子页面
     */
    @RequestMapping(value = "putaway-edit", method = RequestMethod.GET)
    public ModelAndView showPutaway(@RequestParam(required = false) String carid) {
        Map<String, Object> map = new HashMap<String, Object>();
        Car car = carMapper.getCarByCarid(carid);
        CarPrice carPrice = carPriceMapper.getCarPrice(carid);
        // TODO根据clientid获取到ClientUser信息
        ClientUser clientUser = clientUserMapper.getClientByuid(carOwnerMapper
                .getClientid(carid));
        CarDevice carDevice = carDeviceMapper.getCarDevice(carid);
        map.put("car", car);
        map.put("carPrice", carPrice);
        map.put("clientUser", clientUser);
        map.put("carDevice", carDevice);
        return new ModelAndView("putaway-edit", map);
    }

    /**
     * 车辆审核-判断审核是否通过
     */
    @RequestMapping(value = "/car/{carid}", method = RequestMethod.PUT)
    public void editCar(@PathVariable("carid") String carid,
            @RequestBody Car car,HttpServletRequest request) {
        car.setCarid(carid);
        System.out.println("审核通过"+carid);
        carMapper.editCar(car);
        //TODO添加日志信息
        Map<String,Object> editMap = new HashMap<String,Object>();
        editMap.put("logid", UUID.randomUUID().toString());
        editMap.put("businame", "修改车辆状态");
        editMap.put("busitype", "添加");
        editMap.put("busiconent","修改车辆状态");
        BusiLogUtil.addBusiLog(request, busiLogMapper, editMap);
    }

    /**
     * 车辆上架-车辆上架、下架修改车辆状态
     */

    @RequestMapping(value = "/carupPutaway/{carid}", method = RequestMethod.PUT)
    public void carPutaway(@PathVariable("carid") String carid,
            @RequestParam(required = false) String dayprice,
            @RequestParam(required = false) String tempmoney,
            @RequestParam(required = false) String rulemoney,
            @RequestParam(required = false) String basicinsure,
            @RequestParam(required = false) String deviceid,
            @RequestParam(required = false) String simcard,
            @RequestParam(required = false) String timeoutmoney,
            @RequestParam(required = false) String ownermoney,
            @RequestParam(required = false) String discount,
            @RequestParam(required = false) int carstate,
            HttpServletRequest request) {
        Map<String, String> carpriceMap = new HashMap<String, String>();
        carpriceMap.put("carid", carid);
        carpriceMap.put("dayprice", dayprice);
        carpriceMap.put("rulemoney", rulemoney);
        carpriceMap.put("basicinsure", basicinsure);
        carpriceMap.put("timeoutmoney", timeoutmoney);
        carpriceMap.put("ownermoney", ownermoney);
        carpriceMap.put("discount", discount);
        carPriceMapper.addCarPrice(carpriceMap);
      //TODO添加日志信息
        Map<String,Object> editMap2 = new HashMap<String,Object>();
        editMap2.put("logid", UUID.randomUUID().toString());
        editMap2.put("businame", "添加车辆定价信息");
        editMap2.put("busitype", "添加");
        editMap2.put("busiconent","添加车辆定价信息");
        BusiLogUtil.addBusiLog(request, busiLogMapper, editMap2);
        Map<String, String> cardeviceMap = new HashMap<String, String>();
        cardeviceMap.put("carid", carid);
        cardeviceMap.put("deviceid", deviceid);
        cardeviceMap.put("simcard", simcard);
        carDeviceMapper.addCarDevice(cardeviceMap);
      //TODO添加日志信息
        Map<String,Object> editMap1 = new HashMap<String,Object>();
        editMap1.put("logid", UUID.randomUUID().toString());
        editMap1.put("businame", "添加车辆设备信息");
        editMap1.put("busitype", "添加");
        editMap1.put("busiconent","添加车辆设备信息");
        BusiLogUtil.addBusiLog(request, busiLogMapper, editMap1);
        Car car = new Car();
        car.setCarid(carid);
        car.setCarstate(carstate);
        carMapper.setCarState(car);
      //TODO添加日志信息
        Map<String,Object> editMap = new HashMap<String,Object>();
        editMap.put("logid", UUID.randomUUID().toString());
        editMap.put("businame", "修改车辆状态");
        editMap.put("busitype", "添加");
        editMap.put("busiconent","修改车辆状态");
        BusiLogUtil.addBusiLog(request, busiLogMapper, editMap);
    }
    /**
     * 返回car-list页面
     * @author LPX
     * @return 页面
     */
    @RequestMapping(value="/car-list", method=RequestMethod.GET)
	public ModelAndView carList() {	
		return new ModelAndView("car-list");
	}
    /**
     * 返回car-add页面
     * @author LPX
     * @return 页面
     */
	@RequestMapping(value="/car-adds", method=RequestMethod.GET)
	public ModelAndView carAdd() {
		return new ModelAndView("car-adds");
	}
	/**
     * 返回car-edit页面
     * @author LPX
     * @return 页面
     */
	@RequestMapping(value="/car-edit", method=RequestMethod.GET)
	public ModelAndView carAlter(@RequestParam(required=false) String carid) {
		Car car = carMapper.getCarById(carid);		
		System.out.println(car.getDayprice());
		Map<String,Car> modelMap = new HashMap<String,Car>();
		modelMap.put("car", car);		
		
	return new ModelAndView("car-edit",modelMap);
	}
	
	@RequestMapping(value="/getCarBycarcode", method=RequestMethod.GET)
	public PageInfo<Car> carByName(@RequestParam String carcode,@RequestParam  int pageNum,@RequestParam  int pageSize){
	      PageHelper.startPage(pageNum, pageSize);
	      List<Car> carList = carMapper.getCar(carcode);
	      PageInfo<Car> page = new PageInfo<Car>(carList);
	      return page;
	}
	
	/**
     * 模块：车辆管理text
     * 功能：车辆添加
     * @param car
     * @author LPX
     *  
     */
    @RequestMapping(value = "/addCars" ,method=RequestMethod.POST)
    public void addCars(@RequestBody Car car){
    	
    	  	
    	car.setCarid(UUID.randomUUID().toString());
    	String carpics = car.getPicid();
    	String[] pics = carpics.split(",");
    	car.setPicid(pics[0]);
    	car.setCarstate(6);
    	carMapper.addCars(car);
    	
    	//添加车辆日租金
    	CarPrice carPrice = new CarPrice();
    	carPrice.setCarid(car.getCarid());
    	carPrice.setDayprice(car.getDayprice());
    	carPriceMapper. addCarPrices(carPrice);        	
    	
    	//添加图片
    	for(String pic:pics){
    		CarPic carPic = new CarPic();
    		carPic.setPicId(pic.substring(0,pic.lastIndexOf(".")+1));
    		carPic.setPicName(pic);
    		carPic.setPicUrl(env.getProperty("jkd.paths.readFiles"));
    		carPic.setCarId(car.getCarid());
    		carPicMapper.addCarPics(carPic);
    	}   	
    }
    /**
     * 模块：车辆管理
     * 功能：车辆删除
     * @param car
     * @author LPX
     *  
     */
    @RequestMapping(value = "/delCar" ,method=RequestMethod.POST)
    public void delCar(@RequestParam String carid){    	
    	carMapper.delCar(carid);
    }
    
    /**
     * 模块：车辆管理
     * 功能：车辆批量删除
     * @param car
     * @author LPX
     *  
     */
    @RequestMapping(value = "/delCars" ,method=RequestMethod.POST)
    public void delCars(@RequestParam String carid){    	
    	List<String> recordidList = Arrays.asList(carid.split(","));
    	carMapper.delCars(recordidList);
    }
    
    /**
     * 模块：车辆管理
     * 功能：车辆修改
     * @param car
     * @author LPX
     *  
     */
    @RequestMapping(value ="/editCar/{carid}" ,method=RequestMethod.PUT)
    public void editCarPrice (@PathVariable("carid") String carid, @RequestBody Car car){
    	
    	
    	
    	CarPrice carPrice = new CarPrice();
    	carPrice.setCarid(car.getCarcode());
    	carPrice.setDayprice(car.getDayprice());
    	carPriceMapper.editCarPrice(carPrice);   	
    	car.setCarid(carid);
    	carMapper.editCars(car);
    }
    @RequestMapping(value="/car", method=RequestMethod.GET)
	public Map<String,Object> getLikecar(@RequestParam String carstate,@RequestParam String carcode,@RequestParam int draw,@RequestParam int start,@RequestParam int length){
		  Map<String,String> params =  new HashMap<String,String>();
		  params.put("carcode", carcode);
		  params.put("carstate", carstate);
		  
		
		  int pageNum = (start/length)+1;
		  int pageSize = length;		 
		  
	      PageHelper.startPage(pageNum, pageSize);
	      List<Car> carList = carMapper.searchCar(params);
	      PageInfo<Car> page = new PageInfo<Car>(carList);
	      
	      Map<String,Object> rsMap = new HashMap<String,Object>();
	      rsMap.put("draw",draw);
	      rsMap.put("data", page.getList());	      
	      rsMap.put("recordsTotal", page.getTotal());
	      rsMap.put("recordsFiltered", page.getTotal());
	      return rsMap;
	}
	/**
     * 模块：车辆管理
     * 功能：通过查询车辆判断车辆是否存在
     * @param true/false
     * @author LPX
     *  
     */
    @RequestMapping(value = "/getCarsByIdcar" ,method=RequestMethod.POST)
    public  Map<String,String> getCarsById(@RequestParam String carid){    	
    	Car car =carMapper.getCarById(carid);
    	Map<String,String> map = new HashMap<String,String>();
    	if(car!=null){
    		map.put("flag","false");
    		return map;
    	}
    	map.put("flag","true");
    	return map;
    }
}
